package utils

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/spf13/viper"
	"time"
)

// func SECRETKEY ()string  {
// 加密值
func secretKey() string {
	return viper.GetString("jwt.jwt-key")
}

func tokenExpired() int64 {
	return viper.GetInt64("jwt.token-expired-in")
}

// }
// 自定义Claims
type CustomClaims struct {
	Uid   string
	Scope string
	UName string
	jwt.StandardClaims
	Token string
}

func NewJwt() *CustomClaims {
	//生成token 过期时间
	maxAge := tokenExpired()
	return &CustomClaims{
		Scope: "8888",
		UName: "昵称",
		Uid:   "0", //用户id
		StandardClaims: jwt.StandardClaims{
			//ExpiresAt: 1694253817, //测试过期时间，使用中药创建一个超过当前的时间
			ExpiresAt: time.Now().Add(time.Duration(maxAge) * time.Second).Unix(), // 过期时间，必须设置
			Issuer:    "jerry",                                                    // 非必须，也可以填充用户名，
		},
	}
}
func (c *CustomClaims) SetUid(uid string) *CustomClaims {
	c.Uid = uid
	return c
}
func (c *CustomClaims) SetScope(scope string) *CustomClaims {
	c.Scope = scope
	return c
}
func (c *CustomClaims) SetUName(uname string) *CustomClaims {
	c.UName = uname
	return c
}
func (c *CustomClaims) SetExpiresAt(ExpiresAt int64) *CustomClaims {
	c.ExpiresAt = ExpiresAt
	return c
}
func (c *CustomClaims) SetIssuer(Issuer string) *CustomClaims {
	c.Issuer = Issuer
	return c
}
func (c *CustomClaims) CreateToken() (*CustomClaims, error) {

	//采用HMAC SHA256加密算法
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	tokenString, err := token.SignedString([]byte(secretKey()))
	if err != nil {
		fmt.Println(err)
		return c, err
	}
	c.Token = tokenString
	return c, nil
}

// 使用方式
func test() {
	Jwt, err := NewJwt().CreateToken()
	fmt.Printf("token: %v\n", Jwt.Token)
	//解析token
	ret, err := JwtParseToken(Jwt.Token)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("userinfo:%v,%v,%v,%v,%v\n", ret.Uid, ret.Scope, ret.UName, ret.ExpiresAt, ret.IssuedAt)

}

// 解析token
func JwtParseToken(tokenString string) (*CustomClaims, error) {
	if (tokenString == "" || tokenString == "null") || tokenString == "undefined" {
		return nil, errors.New("token不能为空")
	}
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(secretKey()), nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}
